package com.hp.order_service.config;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * WebSocket工具类
 * ServerEndpoint配置websocket的名称，和前台页面对应
 */
@ServerEndpoint(value = "/eshop")
@Component
public class WebSocketUtils {

    //WebSocket的对话对象
    private static Session session = null;

    //建立和前台页面连接后的回调方法
    @OnOpen
    public void onOpen(Session session){
        System.out.println("建立连接"+session);
        //给连接赋值
        WebSocketUtils.session = session;
    }

    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println("收到前台消息：" + message);
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        System.out.println("连接关闭");
        session.close();
    }

    /**
     * 向前台发消息
     * @param message
     * @throws IOException
     */
    public static void sendMessage(String message) throws IOException {
        System.out.println("发送消息：" + message);
        if( WebSocketUtils.session != null) {
            WebSocketUtils.session.getBasicRemote().sendText(message);
        }
    }
}